 package com.cloudinnov.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

/**
 * @author chengning
 * @date 2016年8月3日上午9:23:56
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
public class HttpUtil {
    static final Logger _LOG = LoggerFactory.getLogger(HttpUtil.class);
    private static final CloseableHttpClient httpClient;
    public static final String CHARSET = "UTF-8";
    private static final int TIMEOUT = 6000;
    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    public static String doGet(String url, Map<String, String> params, Map<String, String> header) {
        return doGet(url, params, header, CHARSET);
    }
    public static String doPost(String url, Map<String, String> params, Map<String, String> header) {
        return doPost(url, params, header, CHARSET);
    }
    public static String switchCamera(String indexCode, int screenId) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("index_code", indexCode);
        return doPut(CommonUtils.CMS_URL
                + MessageFormat.format(CommonUtils.CMS_SWITCH_URL, CommonUtils.CMS_TVMALL, screenId), indexCode)
                        .toString();
    }
    public static String selectAllScreens(String twCode) {
        Map<String, String> header = new HashMap<String, String>();
        header.put("Accept", "application/json");
        return doGet(CommonUtils.CMS_URL + CommonUtils.CMS_SCREEN_URL, null, header);
    }
    public static String sendPhoneVerifyCode(String phone, String content) {
        Map<String, String> header = new HashMap<String, String>();
        header.put("apikey", PropertiesUtils.findPropertiesKey("sms_apikey"));
        Map<String, String> params = new HashMap<String, String>();
        params.put("mobile", phone);
        params.put("content", String.format(PropertiesUtils.findPropertiesKey("sms_verify_content"), content));
        params.put("tag", "2");
        return doGet(PropertiesUtils.findPropertiesKey("sms_url"), params, header, CHARSET);
    }
    public static String sendResetPwdVerify(String phone, String content) {
        Map<String, String> header = new HashMap<String, String>();
        header.put("apikey", PropertiesUtils.findPropertiesKey("sms_apikey"));
        Map<String, String> params = new HashMap<String, String>();
        params.put("mobile", phone);
        params.put("content", String.format(PropertiesUtils.findPropertiesKey("sms_resetpwd_content"), content));
        params.put("tag", "2");
        return doGet(PropertiesUtils.findPropertiesKey("sms_url"), params, header, CHARSET);
    }
    /**
     * HTTP Get 获取内容
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> header, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), (String) value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpGet = new HttpGet(url);
            // 设置header
            if (header != null && !header.isEmpty()) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        httpGet.setHeader(entry.getKey(), (String) value);
                    }
                }
            }
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * HTTP Post 获取内容
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doPost(String url, Map<String, String> params, Map<String, String> header, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), (String) value));
                    }
                    
                }
            }
            HttpPost httpPost = new HttpPost(url);
            // 设置header
            if (header != null && !header.isEmpty()) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        httpPost.setHeader(entry.getKey(), (String) value);
                    }
                }
            }
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * HttpClient PUT请求
     * @author huang
     * @date 2013-4-10
     * @return
     */
    public static String doPut(String url, String indexCode) {
        HttpResponse<String> response = null;
        try {
            response = Unirest.put(url).header("accept", "application/json")
                    .header("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
                    .body("Content-Disposition: form-data; name=\"index_code\"\r\n\r\n" + indexCode
                            + "\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--")
                    .asString();
        } catch (UnirestException e) {
            _LOG.error("[method]:doPut\t is Bad", e);
        }
        return response.getStatusText();
    }
    public static void main(String[] args) throws UnirestException {
        /*
         * Map<String, String> param = new HashMap<String, String>(); Map<String, String> header =
         * new HashMap<String, String>(); param.put("mobile", "18630016545"); param.put("content",
         * "【中科云创】您的验证码是4555，有效时间5分钟，请不要告诉他人！"); param.put("tag", "2"); header.put("apikey",
         * PropertiesUtils.findPropertiesKey("sms_apikey")); String getData =
         * doGet(PropertiesUtils.findPropertiesKey("sms_url"),param,header,"UTF-8");
         * System.out.println(getData);
         */
        /*
         * String httpUrl = "http://apis.baidu.com/kingtto_media/106sms/106sms"; String httpArg =
         * "mobile=18630016545&content=%E3%80%90%E5%87%AF%E4%BF%A1%E9%80%9A%E3%80%91%E6%82%A8%E7%9A%84%E9%AA%8C%E8%AF%81%E7%A0%81%EF%BC%9A888888";
         * String jsonResult = request(httpUrl, httpArg); System.out.println(jsonResult);
         */
        System.out.println(switchCamera("1612180254131023075011", 12));
    }
    /**
     * @param urlAll :请求接口
     * @param httpArg :参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", "a0d62e25624e4c0ab566f93fbd72a3b9");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
